import store from '..';

const initialState = {
  comments: {} as Comments,
};

export type ArticleDetailCommentType =
  | { type: 'comment/saveComments'; payload: Comments }
  | { type: 'comment/addComments'; payload: Comment }
  | { type: 'comment/changeCommentsDetail'; payload: any };

// 定义评论返回的值类型
export type Comment = {
  com_id: string;
  content: string;
  reply_count: number;
  pubdate: string;
  is_followed: boolean;
  is_liking: boolean;
  like_count: number;
  aut_id: string;
  aut_name: string;
  aut_photo: string;
};

// 定义评论模块数据类型
export type Comments = {
  total_count: number;
  end_id: string;
  last_id: string;
  results: Comment[];
};
export default function CommentReducer(
  state = initialState,
  action: ArticleDetailCommentType
): typeof initialState {
  switch (action.type) {
    // 获取评论数据
    case 'comment/saveComments':
      return {
        ...state,
        comments: action.payload,
      };

    // 添加评论
    case 'comment/addComments':
      return {
        ...state,
        comments: {
          ...state.comments,
          results: [action.payload, ...state.comments.results],
        },
      };

    // 点赞评论
    case 'comment/changeCommentsDetail':
      // console.log(57, action.payload);

      return {
        ...state,
        comments: {
          ...state.comments,
          results: [
            ...state.comments.results.map((item) => {
              if (item.com_id === action.payload.id) {
                return {
                  ...item,
                  is_liking: action.payload.isliking ? true : false,
                  like_count: action.payload.isliking
                    ? item.like_count + 1
                    : item.like_count - 1,
                };
              } else {
                return item;
              }
            }),
          ],
        },
      };
    default:
      return state;
  }
}
